namespace EyeOpen.Warehouse.Mvc.ViewModel.Controllers
{
	using System;
	using System.Linq;
	using System.Web.Mvc;
	using Data;
	using Domain;

	using EyeOpen.Warehouse.Mvc.ViewModel.Models;

	public class CustomerController : BaseController
	{
		private readonly IWarehouseContext context;

		public CustomerController(IWarehouseContext context)
		{
			this.context = context;
		}

		public ActionResult Index()
		{
			var customerModelList =
			context
				.CustomerRepository
				.ToList()
				.Select(c => new CustomerModel { Name = c.Name });

			return Render("Index", new CustomerListModel(customerModelList));
		}

		public ActionResult Create()
		{
			return Render("Create");
		}

		public ActionResult Save(CustomerModel customerModel)
		{
			if (!ModelState.IsValid)
			{
				return Render("Create");
			}

			var customer = new Customer { Id = Guid.NewGuid(), Name = customerModel.Name };

			context.CustomerRepository.Add(customer);
			context.Commit();

			return Index();
		}

		public ActionResult DeleteAll()
		{
			foreach (var customer in context.CustomerRepository.ToList())
			{
				context.CustomerRepository.Remove(customer);
			}

			context.Commit();

			return Index();
		}

		protected override void Dispose(bool disposing)
		{
			context.Dispose();
		}
	}
}